<template>
  <el-container class="full-container">
    <div id="tree-control" :class="['tree-control', {'treeOpen': treeOpen}]" @click="treeControlClick">
      <i v-if="treeOpen" class="el-icon-d-arrow-left"></i>
      <i v-else class="el-icon-d-arrow-right"></i>
    </div>
    <el-aside id="box" :width="treeOpen?'220px':'0px'" :class="['aside-left', {'aside-left-open': treeOpen}]">
      <div class="drag-btn" id="dragBtn"></div>
      <div class="aside-left-tree">
        <div class="filter-input-wrap">
          <el-input
            v-model="filterText"
            size="mini"
            placeholder="输入关键字过滤"
            clearable
          >
            <el-button slot="append" @click="exportGateway">导出</el-button>
          </el-input>
        </div>
        <el-tree
          ref="tree"
          :data="gatewayTree"
          :props="defaultProps"
          class="area-tree"
          highlight-current
          node-key="label"
          :default-expanded-keys="expandedArray"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        >
          <div slot-scope="{ node, data }" class="el-tree-node__label">
            <i v-if="data.managerConnectionStatus === null || data.managerConnectionStatus === 0" title="未知"
               class="el-icon-remove" style="color: #909399"></i>
            <i v-else-if="data.managerConnectionStatus === 1" title="连接" class="el-icon-success"
               style="color: #67C23A"></i>
            <i v-else-if="data.managerConnectionStatus === 2" title="断开" class="el-icon-error"
               style="color: #F56C6C"></i>
            <i v-if="data.status === 0" title="未知" class="square-status" style="background-color: #909399"></i>
            <i v-else-if="data.status === 1" title="运行" class="square-status" style="background-color: #67C23A"></i>
            <i v-else-if="data.status === 2" title="故障" class="square-status" style="background-color: #F56C6C"></i>
            <i v-else-if="data.status === 3" title="停用" class="square-status" style="background-color: #E6A23C"></i>
            <span :title="node.label">{{ node.label }}</span>
          </div>
        </el-tree>
      </div>
    </el-aside>
    <el-container>
      <el-main v-loading="isSubmitLoading" class="my-main">
        <div v-if="!gatewayId" class="alert-wrap">
          <el-alert
            title="请先选择网关"
            description="展开左侧树形地域结构，选择网关进行操作。"
            show-icon
            type="info"
          >
          </el-alert>
        </div>
        <el-tabs v-if="gatewayId" v-model="activeName" class="my-tab" type="border-card" @tab-click="handleClick">
          <el-tab-pane label="状态" name="first">
            <gate-way-status ref="gateWayStatus" @delete="deleteGateway"></gate-way-status>
          </el-tab-pane>
          <el-tab-pane label="网关配置" name="second">
            <gate-way-config ref="gateWayConfig" :manager-connection-status="managerConnectionStatus" @save="refreshGatewayTree"></gate-way-config>
          </el-tab-pane>
          <el-tab-pane label="数采配置" name="third">
            <port-config ref="portConfig" :manager-connection-status="managerConnectionStatus"></port-config>
          </el-tab-pane>
          <el-tab-pane label="上传配置" name="fourth">
            <upload-service ref="uploadService"></upload-service>
          </el-tab-pane>
          <el-tab-pane label="查看数据" name="fifth">
            <data-element ref="dataElement" :manager-connection-status="managerConnectionStatus"></data-element>
          </el-tab-pane>
          <el-tab-pane label="缓存管理" name="sixth">
            <port-cache ref="portCache" :manager-connection-status="managerConnectionStatus"></port-cache>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
  import { getGatewayTree, exportGateway } from "@/api/gateway";
  import GateWayStatus from "./components/GateWayStatus";
  import GateWayConfig from "./components/GateWayConfig";
  import PortConfig from "../config/collection";
  import UploadService from "../upload/index";
  import DataElement from "../data-element/index";
  import PortCache from "../upload/cache";

  export default {
    components: {
      GateWayStatus,
      GateWayConfig,
      PortConfig,
      UploadService,
      DataElement,
      PortCache
    },
    data() {
      return {
        expandedArray: [],
        filterText: '',
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        treeOpen: true,
        gatewayTree: [],
        gatewayId: undefined,
        managerConnectionStatus: undefined,
        isSubmitLoading: false,
        activeName: 'first'
      };
    },
    computed: {},
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    mounted() {
      this.dragControllerDiv();
    },
    created() {
      this.getGatewayTree();
    },
    methods: {
      treeControlClick(e) {
        const treeControl = document.getElementById('tree-control');
        treeControl.removeAttribute('style');
        this.treeOpen = !this.treeOpen
      },
      dragControllerDiv() {
        const left = document.getElementById('box');
        const resize = document.getElementById('dragBtn');
        const treeControl = document.getElementById('tree-control');
        // 鼠标按下事件
        resize.onmousedown = function (e) {
          var treeControlLeft = treeControl.offsetLeft;
          var startX = e.clientX;
          resize.left = resize.offsetLeft;
          // 鼠标拖动事件
          document.onmousemove = function (e) {
            var endX = e.clientX;
            var moveLen = resize.left + (endX - startX); // （endx-startx）=移动的距离。resize.left+移动的距离=左边区域最后的宽度
            if (moveLen < 140) {
              moveLen = 140;
              treeControl.style.left = '320px';
            } else {
              treeControl.style.left = endX - 30 + 'px'; // 设置控制位置
            }// 左边区域的最小宽度为140px
            resize.style.left = moveLen; // 设置左侧区域的宽度
            left.style.width = moveLen + 'px';
          };
          // 鼠标松开事件
          document.onmouseup = function (evt) {
            document.onmousemove = null;
            document.onmouseup = null;
            resize.releaseCapture && resize.releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
          };
          resize.setCapture && resize.setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
          return false;
        }
      },
      filterNode(value, data) {
        if (!value || !data.label) return true;
        return data.label.indexOf(value) !== -1;
      },
      getGatewayTree() {
        this.isSubmitLoading = true;
        getGatewayTree().then(result => {
          if (result.length) {
            this.gatewayTree = result;
            this.gatewayTree.map(m => {
              this.expandedArray.push(m.label);
            });
            this.filterTree();
          }
          this.isSubmitLoading = false;
        });
      },
      filterTree() {
        if (this.$route.query.name && this.gatewayTree.length) {
          this.expandedArray = [];
          const labelName = this.$route.query.name;
          const selectedNode = this.gatewayTree.filter(m => m.label === labelName);
          if (selectedNode.length && selectedNode[0].children) {
            this.expandedArray.push(selectedNode[0].label);
            selectedNode[0].children.map(m => {
              this.expandedArray.push(m.label);
              if (m.children && m.children.length) {
                m.children.map(n => {
                  this.expandedArray.push(n.label);
                })
              }
            })
          }
          console.log(this.expandedArray);
        }
        if (this.$route.query.deviceCode && this.gatewayTree.length) {
          this.expandedArray = [];
          const labelName = this.$route.query.deviceCode;
          this.expandedArray.push(labelName);
          const data = {
            gatewayId: this.$route.query.id,
            managerConnectionStatus: Number(this.$route.query.managerConnectionStatus)
          };
          this.handleNodeClick(data);
        }
      },
      handleNodeClick(data) {
        console.log(data);
        if (data.gatewayId) {
          this.gatewayId = data.gatewayId;
          this.managerConnectionStatus = data.managerConnectionStatus;
          this.$nextTick(() => {
            this.$refs['gateWayStatus'].getGatewayStatistics(this.gatewayId);
            this.tabLoad(this.activeName);
          })
        }
      },
      handleClick(tab, event) {
        this.tabLoad(tab.name);
      },
      deleteGateway() {
        this.gatewayId = undefined;
        this.getGatewayTree();
      },
      refreshGatewayTree() {
        this.getGatewayTree();
      },
      exportGateway() {
        const loading = this.$loading({
          lock: true,
          text: '请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.7)'
        });
        exportGateway().then(result => {
          this.download(result, '网关列表.xlsx');
          loading.close();
        });
      },
      download(data, name) {
        const blob = new Blob([data]);
        const fileName = name;
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      },
      tabLoad(nowTab) {
        console.log(nowTab);
        switch (nowTab) {
          case 'first':
            this.$refs['gateWayStatus'].getGatewayStatistics(this.gatewayId);
            break;
          case 'second':
            this.$refs['gateWayConfig'].getGateway(this.gatewayId);
            break;
          case 'third':
            this.$refs['portConfig'].reSetGateway(this.gatewayId);
            break;
          case 'fourth':
            this.$refs['uploadService'].getNorthboundWithEquipment(this.gatewayId);
            break;
          case 'fifth':
            this.$refs['dataElement'].getAllEquipmentShort(this.gatewayId);
            break;
          case 'sixth':
            this.$refs['portCache'].getNorthboundCache(this.gatewayId);
            break;
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .aside-left-tree{
    button{
      padding: 10px;
    }
  }
  .full-container {
    position: relative;
    min-height: calc(100vh - 50px);
  }

  .aside-left {
    position: relative;
    margin-bottom: 0;
    box-shadow: -10px 0 10px #4e678433 inset;
    transition: all 0.28s;
    padding: 0;
    overflow: hidden;

    &.aside-left-open {
      padding: 8px 10px;
    }
  }

  .aside-header {
    display: flex;
    align-items: center;
    font-weight: bold;

    &:before {
      content: '';
      display: inline-block;
      margin-right: 5px;
      width: 4px;
      height: 16px;
      background-color: #000000;
    }
  }

  .area-tree {
    background-color: transparent;

    .square-status {
      display: inline-block;
      line-height: 1;
      width: 10px;
      height: 10px;
    }
  }

  .my-main {
    padding: 0;

    .my-tab {
      box-shadow: none;
      border-width: 1px 0 0;

      .el-tabs__content {
        padding: 20px;
      }
    }
  }

  .alert-wrap {
    margin: 20px;
  }

  .filter-input-wrap {
    margin-bottom: 10px;
  }

  .drag-btn {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    width: 1px;
    background-color: transparent;
    z-index: 1;
    cursor: col-resize;
  }
</style>
